package com.htx.zqs.blesmartmask.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Environment;
import android.util.Log;
import android.view.View;

import com.htx.zqs.blesmartmask.R;
import com.htx.zqs.blesmartmask.listeners.OkListener;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import timber.log.Timber;

//import cn.quicknew.serialporttestapk.app.Preferences;

/**
 * Created by Administrator on 2017/10/13.
 */

public class OkhttpUtils implements Callback {

    private final OkHttpClient okHttpClient;
    private static final long cacheSize = 1024 * 1024 * 20;// 缓存文件最大限制大小20M
    private static String cacheDirectory = Environment.getExternalStorageDirectory() + "/okttpcaches"; // 设置缓存文件路径
    private static Cache cache = new Cache(new File(cacheDirectory), cacheSize);  //
    private Request request;
    MediaType jsonType = MediaType.parse("application/json; charset=utf-8");

    int RequestCode;
    Activity activity;
    AlertDialog.Builder builder;
    private AlertDialog show;
    View view;
    OkListener mListner;

    public OkhttpUtils(Activity activity, int RequestCode, OkListener mListener) {
        okHttpClient = new OkHttpClient();
        this.RequestCode = RequestCode;
        this.mListner = mListener;
        this.activity = activity;
    }


    /**
     * GET 请求
     *
     * @param RequestCode
     * @param url
     */
    public void get(int RequestCode, String url) {
        // showProgress();
        //     String accessToken = Preferences.getAccessToken();----保存在本地的token

        Request request = new Request.Builder().url(url).get()
                //强制使用网络响应
//                .header("Cache-Control", "no-cache") // 刷新数据
                //          .header("Authorization","Bearer "+accessToken)
                .build();
        //通过服务器验证缓存数据是否有效
       /*         .header("Cache-Control", "max-age=0")
                .build();*/
        // 强制使用缓存响应
            /*    .header("Cache-Control", "only-if-cached")
                .build();*/
        //指定缓存数据过时的时间
     /*   int maxStale = 60 * 60 * 24 * 28; //4周
                .header("Cache-Control", "max-stale=" + maxStale)
                .url("http://publicobject.com/helloworld.txt")
                .build();*/
        Call call = okHttpClient.newCall(request);
        call.enqueue(new OkhttpUtils(activity, RequestCode, mListner));
    }

    /**
     * POST 提交json形式
     *
     * @param RequestCode
     * @param url
     * @param json
     */
    public void postJson(int RequestCode, String url, String json) {
        //String accessToken = Preferences.getAccessToken();
        okHttpClient.newBuilder()
                .connectTimeout(5, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .build();
        RequestBody body = RequestBody.create(jsonType, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                //    .header("Authorization","Bearer "+accessToken)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new OkhttpUtils(activity, RequestCode, mListner));
    }

    public static void postJson( String url, String json,Callback callback) {
        OkHttpClient okHttpClient  = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10,TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .build();

        //MediaType  设置Content-Type 标头中包含的媒体类型值
        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
                , json);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        Call call = okHttpClient.newCall(request);
        //加入队列 异步操作
        call.enqueue(callback);
    }

    /**
     * POST 提交表单形式
     *
     * @param RequestCode
     * @param url
     * @param map
     */
    public void postForm(int RequestCode, String url, HashMap<String, String> map) {
        Timber.e("请求，url:" + url + "   ----map:" + map);
        okHttpClient.newBuilder()
                .connectTimeout(5, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .build();

        FormBody.Builder builder = new FormBody.Builder();

        Iterator iter = map.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            Object key = entry.getKey();
            Object val = entry.getValue()==null?"": entry.getValue();
            builder.add(key.toString(), val.toString());
        }

        FormBody formBody = builder.build();
        Request request = new Request.Builder()
                .url(url)//请求的url
                .post(formBody)
                .build();
        //创建/Call
        Call call = okHttpClient.newCall(request);
        call.enqueue(new OkhttpUtils(activity, RequestCode, mListner));
    }


    @Override
    public void onFailure(Call call, final IOException e) {
        if (mListner != null) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mListner.onError(RequestCode, e);
                }
            });
        }
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        if (mListner != null) {
            int code = response.code();
            ResponseBody body = response.body();
            if (code == 200) {
                final String string = body.string();
                Timber.e("返回，body:" + string);
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mListner.onSuccess(RequestCode, string);
//                    if (show != null) {
//                        show.dismiss();
//                    }
                    }
                });
            } else {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mListner.onError(RequestCode, new IOException(activity.getResources().getString(R.string.error_message)));
                    }
                });
            }

        }
    }
}
